
// Copyright (C) Recursion Company. All rights reserved.

#include "stdafx.h"
#include "vol_user_app_info.h"

//-----------------------------------------------------------------------------------------

CVWnd_DatePicker::CVWnd_DatePicker ()
{
    m_dbCurrentDate = m_dbMinDate = m_dbMaxDate = 0;
    m_dtLastNotify = 0;
    m_blpNotifying = FALSE;
}

BOOL CVWnd_DatePicker::SetTime (const DOUBLE dbTimeNew)
{
	SYSTEMTIME sysTime;
    DWORD dwFlags;
    if (IsDoubleEqualZero (dbTimeNew))
    {
        ::GetLocalTime (&sysTime);
        dwFlags = GDT_VALID;
    }
    else
	    dwFlags = (::VariantTimeToSystemTime (dbTimeNew, &sysTime) ? GDT_VALID : GDT_NONE);

	return CDateTimePickerCtrl::SetSystemTime (dwFlags, &sysTime);
}

DOUBLE CVWnd_DatePicker::GetTime ()
{
    SYSTEMTIME sysTime;
    if (CDateTimePickerCtrl::GetSystemTime (&sysTime) == GDT_VALID)
    {
        DOUBLE dbDate;
        if (AtlConvertSystemTimeToVariantTime (sysTime, &dbDate))
            return dbDate;
    }

    return 0;
}

BOOL CVWnd_DatePicker::CreateControl (CVolNativeWndCreateParam* pCreateParam)
{
    m_dtLastNotify = 0;

    if (_CREATE_WND_BY_PARAM (pCreateParam) != NULL)
    {
        ModifyWndStyleEx (this, 0, pCreateParam->m_dwExStyle);

        UpdateRange ();
        SetTime (m_dbCurrentDate);

        return TRUE;
    }

    return FALSE;
}

void CVWnd_DatePicker::UpdateRange ()
{
    if (m_hWnd != NULL)
    {
	    SYSTEMTIME sysTimes [2];
        WPARAM wFlags = 0;

	    if (IsDoubleEqualZero (m_dbMinDate) == FALSE && ::VariantTimeToSystemTime (m_dbMinDate, &sysTimes [0]))
			wFlags |= GDTR_MIN;

	    if (IsDoubleEqualZero (m_dbMaxDate) == FALSE && ::VariantTimeToSystemTime (m_dbMaxDate, &sysTimes [1]))
			wFlags |= GDTR_MAX;

	    ::SendMessage (m_hWnd, MCM_SETRANGE, wFlags, (LPARAM)sysTimes);
    }
}

LRESULT CVWnd_DatePicker::OnMyDateTimeChange (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    if (m_blpNotifying == FALSE)
    {
        const DOUBLE dtCurrent = GetTime ();

        if (IsDoubleEqualZero (m_dtLastNotify) || IsDoubleEqual (dtCurrent, m_dtLastNotify) == FALSE)
        {
            m_blpNotifying = TRUE;
            if (m_pEventListener != NULL)
                m_pEventListener->OnDateChanged ();
            m_blpNotifying = FALSE;

            m_dtLastNotify = dtCurrent;
        }
    }

    return 0;
}

LRESULT CVWnd_DatePicker::OnDatetimechange (LPNMHDR pnmh)
{
    PostMessage (MWM_DATE_TIME_CHANGE, 0, 0);
    return 0;
}

LRESULT CVWnd_DatePicker::OnKillfocus (LPNMHDR pnmh)
{
    SendKillFocusNativeMessage (m_hWnd, m_pEventListener);
    return 0;
}

LRESULT CVWnd_DatePicker::OnSetfocus (LPNMHDR pnmh)
{
    SendSetFocusNativeMessage (m_hWnd, m_pEventListener);
    return 0;
}
